/*
 * File:   ipc_manager.cpp
 * Author: dolphinigle
 *
 * Created on December 3, 2011, 7:42 AM
 */

#include "ipc_manager.h"

#include <cstdlib>
#include <string>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <cstdio>
using std::string;

void IPCManager::SendMessage(string message) {
  // Format:
  string l = "";
  int len = (int)message.size();

  while (l.size() < kMessageLengthLength) {
    string str = "";
    str += (char)((len % 10) + '0');
    l = str + l;
    len /= 10;
  }

  buffer_.type = 1;
  for (int i = 0; i < kMessageLengthLength; ++i) {
    buffer_.text[i] = l[i];
  }

  if (msgsnd(target_msq_id_ , &buffer_, kMessageLengthLength,
      IPC_NOWAIT) < 0) {
    printf("msgsnd error\n");
    exit(2);
  }

  buffer_.type = 1;
  for (size_t i = 0; i < message.size(); ++i) {
    buffer_.text[i] = message[i];
  }
  if (msgsnd(target_msq_id_, &buffer_, message.size(), IPC_NOWAIT) < 0) {
    printf("msgsnd error\n");
    exit(2);
  }
}

string IPCManager::ReceiveMessage() {
  if (msgrcv(input_msq_id_, &buffer_, /* length = */ kMessageLengthLength,
             /* type = */ 1, /* flag = */ 0) < 0) {
    printf("msgrcv error up\n");
    exit(3);
  }

  int len = 0;
  for (int i = 0; i < kMessageLengthLength; ++i) {
    len *= 10;
    len += (int)(buffer_.text[i] - '0');
  }

  assert(len < kMaxMessageSize);
  if (msgrcv(input_msq_id_, &buffer_, /* length = */ len, /* type = */ 1,
             /* flag = */ 0) < 0) {
    printf("msgrcv error down\n");
    exit(3);
  }

  string hasil = "";
  for (int i = 0; i < len; ++i) hasil += buffer_.text[i];
  return hasil;
}
